<template>
  <div class="container main-wrapper">
    <div class="page-wrapper">
      <div class="container-fluid">
        <div class="row">
          <!-- 视频预览列 -->
          <div class="col-12 col-lg-6 preview-wrapper">
            <!-- 视频预览区域 -->
            <div class="row">
              <div class="preview-pushlishInfo col-lg-12 col-6">
                
                <div class="preview-content">
                  <div id="localVideo"></div>
                </div>
              </div>
            </div>
          </div>
          <!-- 操作按钮列 -->
          <div class="col-12 col-lg-6 action-wrapper">
            <!-- 登录房间操作步骤 -->
            <div class="action-step">
              <div class="action-title">
                <span class="action-info">Login Room</span>
              </div>
              <div class="action-content">
                <!-- 登录按钮 -->
                <button
                  id="LoginRoom"
                  class="play-pause-button"
                  @click="loginRoom"
                >
                  <div
                    class="success-svg m-r-5"
                    id="loginSuccessSvg"
                    v-if="isLogin"
                  >
                    <svg
                      class="ft-green-tick"
                      xmlns="http://www.w3.org/2000/svg"
                      height="15"
                      width="15"
                      viewBox="0 0 48 48"
                      aria-hidden="true"
                    >
                      <circle
                        class="circle"
                        fill="#5bb543"
                        cx="24"
                        cy="24"
                        r="22"
                      />
                      <path
                        class="tick"
                        fill="none"
                        stroke="#FFF"
                        stroke-width="6"
                        stroke-linecap="round"
                        stroke-linejoin="round"
                        stroke-miterlimit="10"
                        d="M14 27l5.917 4.917L34 17"
                      />
                    </svg>
                  </div>
                  {{ isLogin ? "Logout Room" : "Login Room" }}
                </button>
              </div>
            </div>
            <!-- 开始发布流操作步骤 -->
            <div class="action-step">
              <div class="action-title">
                <span class="action-info">Start Publishing Stream</span>
              </div>
              <div class="action-content">
                <!-- 流发布设置 -->
                <div class="publish-setting m-t-10">
                  <!-- 麦克风选择 -->
                  <div class="font-12 publish-check m-b-15">
                    <div class="check-wrappre m-r-5">
                      <label class="form-check-label m-r-5" for="Microphone"
                        >Microphone</label
                      >
                      <input
                        class="check-input"
                        type="checkbox"
                        v-model="microphoneEnabled"
                      />
                    </div>
                  </div>
                </div>
                <!-- 开始发布按钮 -->
                <button
                  id="startPublishing"
                  class="play-pause-button"
                  @click="startPublishingStream"
                >
                  {{ published ? "Stop Publishing" : "Start Publishing" }}
                </button>
                <!-- 麦克风切换设置 -->
                <div class="font-12 select-wrapper">
                  <span>Microphone Switch</span>
                  <select
                    class="form-control form-control-sm m-l-5"
                    v-model="microphoneDeviceID"
                  >
                    <option
                      v-for="device in microphoneDevices"
                      :key="device.deviceID"
                      :value="device.deviceID"
                    >
                      {{ device.deviceName }}
                    </option>
                  </select>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ZegoExpressEngine } from "zego-express-engine-webrtc";

export default {
  data() {
    return {
      userID: "",
      token: "",
      roomID: "",
      streamID: "", // 流ID将与房间ID相同
      zg: null,
      localStream: null,
      isLogin: false,
      published: false,
      cameraEnabled: true,
      microphoneEnabled: true,
      microphoneDeviceID: "",
      microphoneDevices: [],
      videoCodec: "VP8",
    };
  },
  methods: {
    getUrlParams() {
      const urlParams = new URLSearchParams(window.location.hash.split('?')[1]);
      const linkId = urlParams.get('linkId');
      const userId = urlParams.get('userId');
      if (linkId) {
        this.roomID = linkId;
        this.streamID = linkId;
      }
      if (userId) {
        this.userID = userId;
      }
    },
    async createZegoExpressEngine() {
      this.zg = new ZegoExpressEngine(
        432857160,
        "e274f9f87b331d97dcfa56d50a93697a03ce8b9143f50dcfa84851973fa5a77b"
      );
      window.zg = this.zg;
    },
    async checkSystemRequirements() {
      console.log("sdk version is", this.zg.getVersion());
      try {
        const result = await this.zg.checkSystemRequirements();
        console.warn("checkSystemRequirements ", result);
        if (!result.webRTC) {
          console.error("browser is not support webrtc!!");
          return false;
        } else if (!result.videoCodec.H264 && !result.videoCodec.VP8) {
          console.error("browser is not support H264 and VP8");
          return false;
        } else if (!result.camera && !result.microphone) {
          console.error("camera and microphones not allowed to use");
          return false;
        }
        return true;
      } catch (err) {
        console.error("checkSystemRequirements", err);
        return false;
      }
    },
    async enumDevices() {
      const audioInputList = [];
      const deviceInfo = await this.zg.enumDevices();
      deviceInfo &&
        deviceInfo.microphones.map((item, index) => {
          if (!item.deviceName) {
            item.deviceName = "microphone" + index;
          }
          audioInputList.push({
            deviceID: item.deviceID,
            deviceName: item.deviceName,
          });
          console.log("microphone: " + item.deviceName);
          return item;
        });
      this.microphoneDevices = audioInputList;
    },
    initEvent() {
      this.zg.on("roomStateUpdate", (roomId, state) => {
        if (state === "CONNECTED") {
          console.log(111);
          this.isLogin = true;
        } else if (state === "DISCONNECTED") {
          this.isLogin = false;
        }
      });
      this.zg.on("publisherStateUpdate", (result) => {
        if (result.state === "PUBLISHING") {
          this.published = true;
        } else if (result.state === "NO_PUBLISH") {
          this.published = false;
        }
      });
    },
    async loginRoom() {
      if (!this.isLogin) {
        try {
          await this.getToken();
          if (!this.token) {
            console.error("Token is empty");
            this.$message.error("Token is empty");
            return;
          }
          await this.zg.loginRoom(this.roomID, this.token, {
            userID: this.userID,
            userName: this.userID,
          });
          this.isLogin = true;
        } catch (err) {
          console.error("Login failed", err);
          this.isLogin = false;
        }
      } else {
        this.logoutRoom();
      }
    },
    async getToken() {
      const formData = new FormData();
      formData.append("userId", this.userID);
      try {
        const response = await this.$http.post("/streaming/roomManager/getToKen", formData, {
          headers: {
            Authorization: "EduCloudMeet"
          }
        });
        console.log('Token request response:', response);
        if (response.data.code === 200) {
          if (response.data.data) {
            this.token = response.data.data.data;
          } else {
            console.error('Token data is empty in the response.');
            this.$message.error('获取到的Token为空');
          }
        } else {
          console.error('Token request failed:', response.data.msg);
          this.$message.error(response.data.msg);
        }
      } catch (error) {
        console.error('Token request error:', error);
        this.$message.error('请求Token时发生错误');
      }
    },
    async startPublishingStream() {
      if (!this.isLogin) {
        alert("Please login to the room first");
        return;
      }
      if (!this.published) {
        try {
          const config = {
            camera: {
              video: this.cameraEnabled,
              audio: this.microphoneEnabled
                ? { input: this.microphoneDeviceID }
                : false,
            },
          };
          this.localStream = await this.zg.createZegoStream(config);
          this.zg.startPublishingStream(this.roomID, this.localStream, {
            videoCodec: this.videoCodec,
          });
          this.localStream.playVideo(document.getElementById("localVideo"), {
            mirror: true,
            objectFit: "cover",
          });
          this.published = true;
        } catch (err) {
          console.error("Start publishing failed", err);
          this.published = false;
        }
      } else {
        this.stopPublishingStream();
      }
    },
    stopPublishingStream() {
      if (this.localStream) {
        this.zg.stopPublishingStream(this.roomID);
        this.zg.destroyStream(this.localStream);
        this.localStream = null;
        this.published = false;
      }
    },
    logoutRoom() {
      if (this.localStream) {
        this.stopPublishingStream();
      }
      this.zg.logoutRoom(this.roomID);
      this.isLogin = false;
    },
  },
  async mounted() {
    this.getUrlParams(); // 获取 URL 参数
    await this.createZegoExpressEngine();
    await this.checkSystemRequirements();
    await this.enumDevices();
    this.initEvent();
  },
};
</script>

<style scoped>
.pushlishInfo-title {
  font-weight: 500;
}

.preview-content {
  width: auto;
  height: 400px; /* 增大视频窗口 */
  border: 1px solid #ccc;
  margin: 0 auto; /* 居中显示 */
}

.preview-content > video,
#localVideo {
  width: 100%;
  height: 100%;
}

.logger-wrapper {
  margin-top: 20px;
  width: 100%;
  height: 250px;
  background-color: #ccc;
  color: rgb(252, 250, 250);
  overflow: scroll;
}

.btn-wrapper {
  display: flex;
  width: 100%;
  background-color: rgb(252, 250, 250);
  border-radius: 10px;
  height: 30px;
  justify-content: center;
  align-items: center;
}

.action-step {
  margin: 10px 0;
}

.action-content {
  width: 100%;
  background-color: rgb(252, 250, 250);
  border-radius: 10px;
  padding: 10px;
}

.action-title {
  font-weight: 700px;
  color: black;
}

.action-info {
  font-size: 14px;
}

.cuBtn {
  display: block;
  padding: 0 8px; /* 使按钮变小 */
  font-size: 12px; /* 使按钮变小 */
  cursor: pointer;
  height: 25px; /* 使按钮变小 */
  width: 80%; /* 使按钮变小 */
}

.action-room {
  padding-bottom: 15px;
}

.action-room > div + div {
  margin-top: 4px;
}

.icon-question {
  display: inline-block;
  text-align: center;
  line-height: 16px;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background-color: #0575ff;
  color: #fff;
  cursor: pointer;
  font-weight: bold;
}

.icon-question .pop-box {
  visibility: hidden;
  width: 120px;
  background-color: #fff;
  box-shadow: 0 0 10px #dfdfdf;
  color: #000;
  text-align: center;
  border-radius: 6px;
  padding: 4px;
  position: absolute;
  z-index: 1;
  font-weight: 100;
  font-size: 12px;
}

.icon-question:hover .pop-box {
  visibility: visible;
}

input {
  width: 40%;
  height: 21px;
  border: 1px solid #ced4da;
  border-radius: 0.25rem;
  color: #495057;
}

.w-70 {
  width: 70%;
}

.publish-setting {
  display: flex;
  align-items: center;
}

.publish-check {
  flex-basis: 50%;
  display: flex;
  justify-content: space-around;
}

.check-wrappre {
  text-align: center;
  display: flex;
  align-items: center;
}

.check-input {
  display: inline-block;
  width: auto !important;
  height: auto !important;
}

select {
  width: 45% !important;
  height: 21px !important;
  padding: 0 !important;
  font-size: 12px !important;
}

.select-wrapper {
  flex-basis: 30%;
  display: flex;
  align-items: center;
  white-space: nowrap;
}

option {
  height: 21px !important;
  font-size: 14px;
}

@media (max-width: 375px) {
  .preview-playInfo {
    margin-top: 0 !important;
  }
}
</style>